<template>
    <div style="padding: 15px;">
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
            <el-row>
                <el-col :span="8">
                  <div class="grid-content bg-purple">
                    <el-form-item
                      label="报损单号"
                      prop="code"
                      style="margin-right: 15px"
                      label-width="120px"
                    >
                      <el-input
                        disabled
                        v-model="form.code"
                        style="width: 100%"
                      ></el-input>
                    </el-form-item>
                  </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content bg-purple">
                        <el-form-item label="仓库" prop="warehouseCode">
                          <warehouseSelect ref="warehouseSelect"  @setWarehouseCode="setWarehouseCode" style="width: 75%"/>
                        </el-form-item>
                    </div>
                </el-col>
            </el-row>


            <el-row>
                  <el-col :span="8">
                    <div class="grid-content bg-purple">
                      <el-form-item  label="入驻商" prop="shipmentCode" style="margin-right: 15px" label-width="120px">
                        <shipmentSelect3 ref="shipmentSelect3" :defaultVal="{ partyCode: form.shipmentCode, userName: form.shipmentName }" @setShipmentInfo="setShipmentInfo" style="width: 75%"/>
                      </el-form-item>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="grid-content bg-purple">
                      <el-form-item label="报损类型" prop="type">
                        <el-select v-model="form.type"
                                   @change="selectDamagedType(form.type)"
                                   placeholder="请选择报损类型"
                                   style="width:75%">
                          <el-option
                            v-for="item in typeList"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                          />
                        </el-select>
                      </el-form-item>
                    </div>
                  </el-col>
                </el-row>
            <el-row>
                <el-col :span="19">
                    <div class="grid-content bg-purple">
                        <el-form-item  label="报损原因" style="margin-right: 15px" label-width="120px">
                            <el-input v-model="form.remarks" style="width:75%"  />
                        </el-form-item>
                    </div>
                </el-col>
            </el-row>
        </el-form>
        <vxe-toolbar id="toolbar_demo3">
        <template v-slot:buttons>
            <el-button @click="insertEvent">新增</el-button>
        </template>
        </vxe-toolbar>

        <vxe-table
                border
                resizable
                show-overflow
                ref="xTable"
                :align="allAlign"
                :data="tableData"
                show-footer
                :footer-method="footerMethod"
                :edit-rules="validRules"
                :edit-config="{trigger: 'click', mode: 'cell'}">
            <vxe-table-column type="seq" width="60"></vxe-table-column>
            <vxe-table-column field="goodsName" title="商品名称" :edit-render="{name: 'ElSelect'}" width="270">
                <template v-slot:edit="{ row }">
                    <goodsSelect  :val2="form.shipmentCode" ref="goodsSelect"  @setGoodsCode="setGoodsCode(row)" />
                </template>
            </vxe-table-column>
            <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
            <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
            <vxe-table-column field="goodsUnitName" title="单位"  width="270" :edit-render="{name: 'ElSelect'}" >
                <template v-slot:edit="{ row }" >
                    <el-select v-model="row.goodsUnitName"
                               @change="selectGoodsUnitCode($event, row)"
                               placeholder="请输入单位"
                               style="width:100%" >
                        <el-option
                                v-for="item in row.goodsUnitConversionList"
                                :key="item.unitCode"
                                :label="item.unitName"
                                :value="{value:item.unitCode,label:item.unitName, basicQuantity:item.quantity}"
                        />
                    </el-select>
                </template>
            </vxe-table-column>
            <vxe-table-column field="unitQuantity" title="数量" :edit-render="{name: 'input'}" width="120"></vxe-table-column>
            <vxe-table-column field="remarks" title="备注" :edit-render="{name: 'input'}" width="270"></vxe-table-column>
            <vxe-table-column title="操作" fixed="right" min-width="150">
                <template slot-scope="scope">
                    <!-- <vxe-button type="text" @click="insertEvent(-1)">
                        <i class="el-icon-plus" />
                    </vxe-button> -->
                    <vxe-button v type="text" @click="removeEvent(scope.row)">
                        <i class="el-icon-minus" />
                    </vxe-button>
                </template>
            </vxe-table-column>
        </vxe-table>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" v-show="form.status == '0'" @click="funcSubmitSave" :disabled="isDisable" plain>保 存</el-button>
            <el-button type="primary" @click="funcSubmitCheck" :disabled="isDisable" plain>提 交</el-button>
        </div>
    </div>
</template>
<script>
    import Vue from 'vue'
    import 'xe-utils'
    import VXETable from 'vxe-table'
    import 'vxe-table/lib/index.css'
    import XEUtils from 'xe-utils'
    import VXEUtils from 'vxe-utils'
    import VXETablePluginElement from 'vxe-table-plugin-element'
    import 'vxe-table-plugin-element/dist/style.css'
    import goodsSelect from '@/views/components/goodsElSelect.vue'
    import { damagedEdit, damagedDetail} from '@/api/store'
    import { validatenumber } from "@/utils/validate.js";
    import {getWarehouse, findShipmentPartys, getDictList} from '@/api/basicInfo'

    import shipmentSelect3 from '@/views/components/shipmentSelect3.vue'
    import warehouseSelect from '@/views/components/warehouseSelect.vue'

    Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
    VXETable.use(VXETablePluginElement)
    export default {
        name: 'Parent',
        components: {
          goodsSelect,
          warehouseSelect,
          shipmentSelect3,
        },
        data() {
            return {
                allAlign:'center',
                warehouseData:[],
                shipmentData:[],
                typeList: [],
                deleteCodes:[],

                dictType: 'damagedType',
                isDisable:false,   //确定键显示按钮
                typeList: [],
                form: {
                    code:'',
                    shipmentCode: '',
                    type:'',
                    warehouseCode:"",
                    deleteCodes:[],

                    supplierCode:'',
                    remarks: '', // 备注
                    damagedItemList: [],
                    damagedBy: '',
                    status: ''
                },
                loading: false,
                tableData: [],
                rules: {
                    code: [
                        { required: true, message: '', trigger: 'change' }
                    ],
                    shipmentCode: [
                        { required: true, message: '请输入入驻商', trigger: 'change' }
                    ],
                    warehouseCode: [
                        { required: true, message: '请选择仓库', trigger: 'change' }
                    ],
                    type: [
                        { required: true, message: '请选择报损类型', trigger: 'change' }
                    ]
                },
                validRules: {
                    goodsName: [
                        { required: true, message: '商品名称必须填写' },
                    ],
                    goodsUnitName: [
                        { required: true, message: '单位必须填写' },
                    ],
                    unitQuantity: [
                        { required: true, message: '数量必须填写' },

                        { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数量必须大于0' },
                        { max: 10, message: '数量不能超过10位'}
                    ],
                }
            }
        },
        created() {
          this.getDictList(this.dictType);
        },
        methods: {
          // 选择入驻商
          setShipmentInfo(info) {
            new Promise((resolve)=>{
              if(this.form.shipmentCode === info.partyCode){
               }else{
                this.form.shipmentCode = info.partyCode;
                this.form.shipmentName = info.userName;
                this.tableData = [];
                this.totalRowNum = 0;
                this.$refs.warehouseSelect.init(this.form.shipmentCode)
                resolve()
              }

            })
          },

          // 选择仓库
          setWarehouseCode(value){
            new Promise((resolve)=>{
              if(this.form.warehouseCode === value){
              } else{
                this.form.warehouseCode = value;
                this.tableData = [];
                this.totalRowNum = 0;
                this.form.shipmentCode = '';
                this.form.shipmentName = '';
                this.$refs.shipmentSelect3.setSelectValue(this.form.warehouseCode, this.form.shipmentCode);
                resolve()
              }
            })
          },
            // 单据类型字典查询
            getDictList(dictType){
                getDictList(dictType).then(response => {
                    this.typeList = response.data[0].dictList;
                    this.getInfo();
                })
            },
            // 选择报损类型
            selectDamagedType(val) {
                this.form.type = val;
            },
            // 获取页面信息
            getInfo() {
                this.loading = true;
                let code = this.$route.query.code ? this.$route.query.code : "";
                damagedDetail(code).then(response => {
                  this.form = response.data;
                  this.tableData = this.form.damagedItemList;
                  this.loading = false;
                    // this.$message({ message: response.msg, type: 'success' })
                  this.$refs.warehouseSelect.setSelectValue(this.form.shipmentCode, this.form.warehouseCode);
                  this.$refs.shipmentSelect3.setSelectValue(this.form.warehouseCode, this.form.shipmentCode);

                })
            },
            // 选择入驻商
            setCustomerCode(value) {
                this.form.shipmentCode = value;
                this.tableData = [];
            },
            // 商品选择
            setGoodsCode(row){
                let obj = this.$refs.goodsSelect.obj
                row.goodsName = obj.value;
                row.goodsCode = obj.code;
                row.goodCode = obj.goodCode;
                row.goodCode = obj.goodCode;
                row.goodsUnit = obj.unitCode;
                row.goodsBarCode = obj.barCode;
                row.basicUnit = obj.unitCode;
                row.basicUnitName = obj.basicUnitName;
                row.expirationQuantity = obj.expirationQuantity;
                row.goodsUnitConversionList = obj.goodsUnitConversionList;
            },
            // 单位选择
            selectGoodsUnitCode(event, row){
                row.goodsUnit = event.value;
                row.goodsUnitName = event.label;
                row.basicQuantity = event.basicQuantity;
            },
            // 公共取消
            fatherItemCancel(modelFlag) {
                switch (modelFlag) {
                    case 'add':
                        this.modelAddFlag = false
                        break
                    case 'edit':
                        this.modelEditFlag = false
                        break
                    default:
                }
            },
            // 新增
            insertEvent (row) {
                if (this.form.shipmentCode && this.form.warehouseCode) {
                    const xTable = this.$refs.xTable
                    const newRow = {
                    }
                    xTable.insert().then(({ row }) => xTable.setActiveRow(row))

                }
            },
            // 删除
            removeEvent (row) {
                this.$XModal.confirm('您确定要删除该数据?').then(type => {
                if (type === 'confirm') {
                    this.$refs.xTable.remove(row)
                }
                if(row.code !== undefined){
                    this.deleteCodes.push(row.code)
                }

        })
            },
            // 保存
            funcSubmitSave() {
                if(this.deleteCodes){
                    this.form.deleteCodes = this.deleteCodes
                }

                this.form.damagedItemList = this.$refs.xTable.tableData;
                const data = this.form
                if (!this.$refs.xTable.tableData.length) {
                    this.$message.error('请新增明细')
                } else {
                    this.$refs['form'].validate((valid) => {
                        if (valid) {
                            this.$refs.xTable.validate((valids) => {
                                if(valids){
                                    this.form.status = 0;
                                    this.isDisable = true;
                                    damagedEdit(data).then(response => {
                                        this.$message({ message: response.msg, type: 'success' })
                                        this.$emit('fatherEditMethod')
                                        this.isDisable = false
                                    }).then(() => {
                                      this.$eventBus.$emit('refreshList')
                                        this.$store.dispatch("tagsView/delView", this.$route);

                                        this.$router.push({
                                            path: "/kngl/damaged"
                                        });
                                    }).catch(() => this.isDisable = false)
                                }else {
                                    return false
                                }
                            })
                        } else {
                            return false
                        }
                    })
                }
            },
            // 提交
            funcSubmitCheck() {
                if(this.deleteCodes){
                    this.form.deleteCodes = this.deleteCodes
                }

                this.form.damagedItemList = this.$refs.xTable.tableData;
                const data = this.form
                if (!this.$refs.xTable.tableData.length) {
                    this.$message.error('请新增明细')
                } else {
                    this.$refs['form'].validate((valid) => {
                        if (valid) {
                            this.$refs.xTable.validate((valids) => {
                                if(valids){
                                    this.form.status = 1;
                                    this.isDisable = true;
                                    damagedEdit(data).then(response => {
                                        this.$message({ message: response.msg, type: 'success' })
                                        this.$emit('fatherEditMethod')
                                        this.isDisable = false
                                    }).then(() => {
                                      this.$eventBus.$emit('refreshList')
                                        this.$store.dispatch("tagsView/delView", this.$route);

                                        this.$router.push({
                                            path: "/kngl/damaged"
                                        });
                                    }).catch(() => this.isDisable = false)
                                }else {
                                    return false
                                }
                            })
                        } else {
                            return false
                        }
                    })
                }
            },
            footerMethod ({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 1) {
                            return '合计'
                        }
                        if (['unitQuantity'].includes(column.property)) {
                              return XEUtils.sum(data, column.property)
                        }
                        return '-'
                    })
                ]
            }
        }
    }
</script>
<style lang="scss" scoped>
    .dialog-footer {
        margin: 150px auto;
        width: 175px;
        // float: right;
    }
</style>

<style>
    .vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
        padding: 6px 0;
    }
    .vxe-toolbar{padding:0 0 10px 0}
</style>
